// DialogQuery.cpp : implementation file
//

#include "stdafx.h"
#include "ECGWorkStation.h"
#include "DialogQuery.h"
#include "..\Public\BiocareDB\BiocareDB.h"
#include "Globals.h"
#include "..\public\DogMaking\DogLib\DogOption.h"
#include "..\public\pubfun\inireadwrite\inireadwrite.h"
#include "MainFrm.h"
#include "ECGFile.h"
#include "ECGDraw.h"
#include "ECGWorkStationView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CDialogQuery dialog

const int DEF_CONTENT_TIME_ONE_WEEK_INDEX = 0;
const CString DEF_CONTENT_TIME_ONE_WEEK = "7";

const int DEF_CONTENT_TIME_TWO_WEEK_INDEX = 1;
const CString DEF_CONTENT_TIME_TWO_WEEK = "14";

const int DEF_CONTENT_TIME_ONE_MONTH_INDEX = 2;
const CString DEF_CONTENT_TIME_ONE_MONTH = "30";

const int DEF_CONTENT_TIME_THREE_MONTH_INDEX = 3;
const CString DEF_CONTENT_TIME_THREE_MONTH = "90";

const int DEF_CONTENT_TIME_NINE_MONTH_INDEX = 4;
const CString DEF_CONTENT_TIME_NINE_MONTH = "270";

CString CONTENT_TIME[] = {DEF_CONTENT_TIME_ONE_WEEK, DEF_CONTENT_TIME_TWO_WEEK,
DEF_CONTENT_TIME_ONE_MONTH, DEF_CONTENT_TIME_THREE_MONTH, 
DEF_CONTENT_TIME_NINE_MONTH};

CDialogQuery::CDialogQuery(CWnd* pParent /*=NULL*/)
	: CDialog(CDialogQuery::IDD, pParent)
{
	//{{AFX_DATA_INIT(CDialogQuery)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
}

CDialogQuery::CDialogQuery(PATIENT_DATA *pPatData, CWnd* pParent, int nQueryType)
: CDialog(CDialogQuery::IDD, pParent)
{
	m_bSelectAll = FALSE;
	m_pPatData = pPatData;
	m_nQueryType = nQueryType;
}

void CDialogQuery::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CDialogQuery)
		// NOTE: the ClassWizard will add DDX and DDV calls here
	//}}AFX_DATA_MAP
}


BEGIN_MESSAGE_MAP(CDialogQuery, CDialog)
	//{{AFX_MSG_MAP(CDialogQuery)
	ON_BN_CLICKED(IDC_BUTTON_QUERY, OnButtonQuery)
	ON_BN_CLICKED(IDC_BUTTON_CLEAR, OnButtonClear)
	ON_BN_CLICKED(IDC_BUTTON_ADD, OnButtonAdd)
	ON_BN_CLICKED(IDC_BUTTON_DELETE, OnButtonDelete)
	ON_BN_CLICKED(IDC_BUTTON_UPDATE, OnButtonUpdate)
	ON_BN_CLICKED(IDC_CHECK_SOMETIME, OnCheckSometime)
	ON_BN_CLICKED(IDC_BUTTON_SEND, OnButtonSend)
	ON_WM_LBUTTONDBLCLK()
	ON_BN_CLICKED(IDC_BUTTON_SELECTALL, OnButtonSelectall)
	ON_BN_CLICKED(IDC_BUTTON_PRINTALL, OnButtonPrintall)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CDialogQuery message handlers

BOOL CDialogQuery::OnInitDialog() 
{
	CDialog::OnInitDialog();
	
	CRect rcList;
	((CStatic*)GetDlgItem(IDC_STATIC_LIST))->GetWindowRect(rcList);
	//ScreenToClient(this->m_hWnd, rcList);
	ScreenToClient(rcList);
	BOOL bRet = m_listQueryResult.Create(WS_CHILD | WS_VISIBLE | WS_BORDER, rcList,this,0x1001);	
	m_listQueryResult.InitializeGrid();
	m_listQueryResult.SetExtendedStyle(LVS_EX_CHECKBOXES|LVS_EX_GRIDLINES);
	InitCtrls();

	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}

void CDialogQuery::OnButtonQuery() 
{
	DoQuery();
}

void CDialogQuery::OnButtonClear() 
{
	((CEdit*)GetDlgItem(IDC_EDIT_PATIENTID))->SetWindowText("");
	((CEdit*)GetDlgItem(IDC_EDIT_NAME))->SetWindowText("");
	((CEdit*)GetDlgItem(IDC_EDIT_AGE))->SetWindowText("");
	((CEdit*)GetDlgItem(IDC_EDIT_STUDYRESULT))->SetWindowText("");

	((CButton*)GetDlgItem(IDC_CHECK_FROM))->SetCheck(FALSE);
	((CButton*)GetDlgItem(IDC_CHECK_FROM))->SetCheck(FALSE);
	if (((CButton*)GetDlgItem(IDC_CHECK_SOMETIME))->GetCheck()) {
		OnCheckSometime();
	}
}

#include "DialogPatInfo.h"
void CDialogQuery::OnButtonAdd() 
{
	PATIENT_DATA patData;
	InitPatientData(&patData);
	int nRet = m_listQueryResult.GetSelectedRecord(&patData);
	if (nRet == LEVEL_NULL || nRet == LEVEL_PATIENT) {
		CDialogPatInfo dlg(PATIENT_INFO_ADD_PATIENT, &patData, this);
		if(dlg.DoModal() == IDOK){
			m_listQueryResult.InsertPatient(&patData);
		}
	}else{
		CDialogPatInfo dlg(PATIENT_INFO_ADD_STUDY, &patData, this);
		if(dlg.DoModal() == IDOK){
			m_listQueryResult.InsertStudy(&patData);
		}
	}
}

void CDialogQuery::OnButtonDelete() 
{
	if(!m_listQueryResult.DeleteSelRecord()){
	}
}

void CDialogQuery::OnButtonUpdate() 
{
	PATIENT_DATA patData;
	InitPatientData(&patData);
	int nRet = m_listQueryResult.GetSelectedRecord(&patData);
	if (nRet == LEVEL_PATIENT) {
		CDialogPatInfo dlg(PATIENT_INFO_EDIT_PATIENT, &patData, this);
		if(dlg.DoModal() == IDOK){
			m_listQueryResult.UpdatePatient(&patData);
		}
	}else if(nRet == LEVEL_STUDY){
		CDialogPatInfo dlg(PATIENT_INFO_EDIT_STUDY, &patData, this);
		if(dlg.DoModal() == IDOK){
			m_listQueryResult.UpdateStudy(&patData);
		}
	}
}

void CDialogQuery::OnOK() 
{
	BeginWaitCursor();
	POSITION pos = m_listQueryResult.GetFirstSelectedItemPosition();
	if (pos != NULL) {
		int nRet = m_listQueryResult.GetSelectedRecord(m_pPatData);
		if (nRet != LEVEL_STUDY && m_nQueryType == QUERY_TYPE_OPEN_STUDY) {
//			InitPatientData(m_pPatData);
		}
	}
	EndWaitCursor();
	
	CDialog::OnOK();
}

void CDialogQuery::OnCheckSometime() 
{
	((CButton*)GetDlgItem(IDC_CHECK_FROM))->SetCheck(FALSE);
	((CButton*)GetDlgItem(IDC_CHECK_TO))->SetCheck(FALSE);

	((CButton*)GetDlgItem(IDC_CHECK_FROM))->EnableWindow(!((CButton*)GetDlgItem(IDC_CHECK_SOMETIME))->GetCheck());
	((CButton*)GetDlgItem(IDC_CHECK_TO))->EnableWindow(!((CButton*)GetDlgItem(IDC_CHECK_SOMETIME))->GetCheck());
	((CDateTimeCtrl*)GetDlgItem(IDC_STUDY_DATEFROM))->EnableWindow(!((CButton*)GetDlgItem(IDC_CHECK_SOMETIME))->GetCheck());
	((CDateTimeCtrl*)GetDlgItem(IDC_STUDY_DATETO))->EnableWindow(!((CButton*)GetDlgItem(IDC_CHECK_SOMETIME))->GetCheck());

	((CComboBox*)GetDlgItem(IDC_COMBO_SOMETIME))->EnableWindow(((CButton*)GetDlgItem(IDC_CHECK_SOMETIME))->GetCheck());
	
}
void CDialogQuery::InitCtrls(void)
{
	if (theApp.m_nUserType == USER_TYPE_NORMAL || theApp.m_nUserType == USER_TYPE_NULL) {
		((CButton*)GetDlgItem(IDC_BUTTON_ADD))->EnableWindow(FALSE);
		((CButton*)GetDlgItem(IDC_BUTTON_DELETE))->EnableWindow(FALSE);
		((CButton*)GetDlgItem(IDC_BUTTON_UPDATE))->EnableWindow(FALSE);
	}
	for (int nLoop = 0; nLoop <= DEF_CONTENT_TIME_NINE_MONTH_INDEX; ++nLoop)
	{
		((CComboBox*)GetDlgItem(IDC_COMBO_SOMETIME))->InsertString(((CComboBox*)GetDlgItem(IDC_COMBO_SOMETIME))->GetCount(), CONTENT_TIME[nLoop]);
	}

	if(m_pPatData == NULL) return;

	BOOL bHaveData = FALSE;
	if(m_pPatData->strName.GetLength() > 0){
		((CEdit*)GetDlgItem(IDC_EDIT_NAME))->SetWindowText(m_pPatData->strName);

		bHaveData = TRUE;
	}

	if(m_pPatData->strPatientID.GetLength() > 0){
		((CEdit*)GetDlgItem(IDC_EDIT_PATIENTID))->SetWindowText(m_pPatData->strPatientID);

		bHaveData = TRUE;
	}

	if(bHaveData) DoQuery();
	else{
		((CButton*)GetDlgItem(IDC_CHECK_FROM))->SetCheck(TRUE);
		((CButton*)GetDlgItem(IDC_CHECK_TO))->SetCheck(TRUE);
	}
}

void CDialogQuery::DoQuery(void)
{
	if (InitDogLincense(DOG_SORFWARE_ECG_MANAGMENT,0,"") != 0) {
 		return;
	}

	m_bSelectAll = FALSE;
	m_listQueryResult.DeleteAll();

	BeginWaitCursor();
	char szErrorMsg[1024];
	memset(szErrorMsg, 0, 1024);
	BOOL bRet = FALSE;
	BCDBConnection DBConn;
	if(!BCDBConnectDB(&DBConn, (LPCTSTR)theApp.m_strConnection, (LPCTSTR)theApp.m_strConnUserName, (LPCTSTR)theApp.m_strConnPassWord, szErrorMsg)){
		return;
	}

	BCDBDataSet* pDataSet = NULL;
	BCDBCreateDataSet(&pDataSet, szErrorMsg);
	BCDBDataSets* pDataSets = NULL;
	BCDBCreateDataSets(&pDataSets, szErrorMsg);
	BCDBDataElem* pDataElem = NULL;

	BOOL bQueryPatientStudy = FALSE;
	CString strPatientName = "", strPatientID = "", strPatientAge = "", strStudyDate = "", strStudyResult = "";
	((CEdit*)GetDlgItem(IDC_EDIT_PATIENTID))->GetWindowText(strPatientID);
	if (strPatientID.GetLength() > 0) {
		BCDBCreateDataElem(&pDataElem, T_PATIENT_ID, strPatientID.GetLength(), DT_STRING, (void*)(LPCTSTR)strPatientID, szErrorMsg);
		pDataSet->push_back(pDataElem); pDataElem = NULL;
	}
	((CEdit*)GetDlgItem(IDC_EDIT_NAME))->GetWindowText(strPatientName);
	if (strPatientName.GetLength() > 0) {
		BCDBCreateDataElem(&pDataElem, T_PATIENT_NAME, strPatientName.GetLength(), DT_STRING, (void*)(LPCTSTR)strPatientName, szErrorMsg);
		pDataSet->push_back(pDataElem); pDataElem = NULL;
	}
	((CEdit*)GetDlgItem(IDC_EDIT_AGE))->GetWindowText(strPatientAge);
	if (strPatientAge.GetLength() > 0) {
		BCDBCreateDataElem(&pDataElem, T_PATIENT_AGE, strPatientAge.GetLength(), DT_STRING, (void*)(LPCTSTR)strPatientAge, szErrorMsg);
		pDataSet->push_back(pDataElem); pDataElem = NULL;
	}
	((CEdit*)GetDlgItem(IDC_EDIT_STUDYRESULT))->GetWindowText(strStudyResult);
	if (strStudyResult.GetLength() > 0) {
		bQueryPatientStudy = TRUE;
		BCDBCreateDataElem(&pDataElem, T_STUDY_PROPRESULT, strStudyResult.GetLength(), DT_STRING, (void*)(LPCTSTR)strStudyResult, szErrorMsg);
		pDataSet->push_back(pDataElem); pDataElem = NULL;
	}
	
	COleDateTime tmFrom, tmTo;
	((CDateTimeCtrl*)GetDlgItem(IDC_STUDY_DATEFROM))->GetTime(tmFrom);
	((CDateTimeCtrl*)GetDlgItem(IDC_STUDY_DATETO))->GetTime(tmTo);

	if (((CButton*)GetDlgItem(IDC_CHECK_SOMETIME))->GetCheck()) {
		COleDateTime tmCurrent = COleDateTime::GetCurrentTime();
		int nCurSel = ((CComboBox*)GetDlgItem(IDC_COMBO_SOMETIME))->GetCurSel();
		if(nCurSel >= 0){
			switch(nCurSel) {
			case 0:
				tmCurrent -= COleDateTimeSpan(7, 0, 0, 0);
				break;
			case 1:
				tmCurrent -= COleDateTimeSpan(14, 0, 0, 0);
				break;
			case 2:
				tmCurrent -= COleDateTimeSpan(30, 0, 0, 0);
				break;
			case 3:
				tmCurrent -= COleDateTimeSpan(90, 0, 0, 0);
				break;
			case 4:
				tmCurrent -= COleDateTimeSpan(270, 0, 0, 0);
				break;
			default:
				break;
			}	

			strStudyDate.Format("%04d%02d%02d-", tmCurrent.GetYear(), tmCurrent.GetMonth(), tmCurrent.GetDay());
		}
	}else {
		if(((CButton*)GetDlgItem(IDC_CHECK_FROM))->GetCheck()){
			strStudyDate.Format("%04d%02d%02d-", tmFrom.GetYear(), tmFrom.GetMonth(), tmFrom.GetDay());
			if(((CButton*)GetDlgItem(IDC_CHECK_TO))->GetCheck()){
				CString strTo = "";
				strTo.Format("%04d%02d%02d", tmTo.GetYear(), tmTo.GetMonth(), tmTo.GetDay());
				strStudyDate += strTo;
			}
		}else if(((CButton*)GetDlgItem(IDC_CHECK_TO))->GetCheck()){
			strStudyDate.Format("-%04d%02d%02d", tmTo.GetYear(), tmTo.GetMonth(), tmTo.GetDay());
		}
	}

	if (strStudyDate.GetLength() > 0) {
		bQueryPatientStudy = TRUE;
		BCDBCreateDataElem(&pDataElem, T_STUDY_DATE, strStudyDate.GetLength(), DT_DATE, (void*)(LPCTSTR)strStudyDate, szErrorMsg);
		pDataSet->push_back(pDataElem); pDataElem = NULL;
	}

	if (bQueryPatientStudy) {
		if(!BCDBQueryPatientStudyData(&DBConn, pDataSet, &pDataSets, szErrorMsg)){
			BCDBDisconnectionDB(&DBConn, szErrorMsg);
			BCDBClearDataSet(pDataSet, szErrorMsg);
			BCDBClearDataSets(pDataSets, szErrorMsg);

			return;
		}
	}else{
		if(!BCDBQueryDBData(&DBConn, T_PATIENT, pDataSet, &pDataSets, szErrorMsg)){
			BCDBDisconnectionDB(&DBConn, szErrorMsg);
			BCDBClearDataSet(pDataSet, szErrorMsg);
			BCDBClearDataSets(pDataSets, szErrorMsg);

			return;
		}
	}

	m_listQueryResult.BuildPatientQueryResultList(pDataSets);

	BCDBClearDataSet(pDataSet, szErrorMsg);
	BCDBClearDataSets(pDataSets, szErrorMsg);
	BCDBDisconnectionDB(&DBConn, szErrorMsg);

	EndWaitCursor();
}

void CDialogQuery::OnButtonSend() 
{
//	BeginWaitCursor();
	POSITION pos = m_listQueryResult.GetFirstSelectedItemPosition();
	if (pos != NULL) {
		int nRet = m_listQueryResult.GetSelectedRecord(m_pPatData);
		if (nRet != LEVEL_STUDY && m_nQueryType == QUERY_TYPE_OPEN_STUDY) {
//			AfxMessageBox("Send dicom file failed - invalidate selected level.");
		}

		CMainFrame* pMainFrame = (CMainFrame*)(AfxGetApp()->m_pMainWnd);
		pMainFrame->SendDicomFile(m_pPatData);
//		CString strLocalAE, strRemoteAE, strRemoteIP, strRemotePort;
//		CIniReadWrite::GetMe()->LoadString(DEF_DICOM_SETTING, DEF_DICOM_LOCAL_AE, &strLocalAE);
//
//		CIniReadWrite::GetMe()->LoadString(DEF_DICOM_SETTING, DEF_DICOM_REMOTE_AE, &strRemoteAE);
//		CIniReadWrite::GetMe()->LoadString(DEF_DICOM_SETTING, DEF_DICOM_REMOTE_PORT, &strRemotePort);
//		CIniReadWrite::GetMe()->LoadString(DEF_DICOM_SETTING, DEF_DICOM_REMOTE_IP, &strRemoteIP);
//		CStoreSCU::Create();
//		DCMObj dcmAssoc;
//		if(CStoreSCU::GetMe()->CreateGeneralDCMAssoc(&dcmAssoc, (char*)(LPCTSTR)strLocalAE, (char*)(LPCTSTR)strRemoteAE, (char*)(LPCTSTR)strRemoteIP, atoi((LPCTSTR)strRemotePort))){
//			CString szDICOMFileName = "TempDICOMFIle.bio";
//			::DeleteFile((LPCSTR)(LPCTSTR)szDICOMFileName);
//			CString strLoadLanguage = "";
//			CIniReadWrite::GetMe()->LoadString(DEF_GENERAL_SETTING, DEF_GENERAL_LOAD_LANGUAGE, &strLoadLanguage);
//			if(ECGDICOMConvert((char*)(LPCTSTR)szDICOMFileName, (void*)m_pPatData, (char*)(LPCTSTR)strLoadLanguage) != ECGDICOM_SUCCESS){
//				AfxMessageBox("Send dicom file failed - can not convert ecg file to dicom file.");
//			}
//
//			if(CStoreSCU::GetMe()->StoreImage(&dcmAssoc, (char*)(LPCTSTR)szDICOMFileName, 1, NULL, 0)){
//				AfxMessageBox("Send dicom file failed - StoreImage.");
//			}
//			CStoreSCU::GetMe()->DestroyGeneralDCMAssoc(&dcmAssoc);
//		}else{
//			AfxMessageBox("Send dicom file failed - CreateGeneralDCMAssoc.");
//		}
//
//		CStoreSCU::Destroy();
	}
//	EndWaitCursor();
}

void CDialogQuery::OnLButtonDblClk(UINT nFlags, CPoint point) 
{
	POSITION pos = m_listQueryResult.GetFirstSelectedItemPosition();
	if (pos != NULL) {
		
		CMainFrame* pMainFrame = (CMainFrame*)(AfxGetApp()->m_pMainWnd);
		int nRet = m_listQueryResult.GetSelectedRecord(&pMainFrame->m_ecgDataDef.ecgPatData);
		if (nRet != LEVEL_STUDY && m_nQueryType == QUERY_TYPE_OPEN_STUDY) {
			//			InitPatientData(m_pPatData);
		}
		if (pMainFrame->m_ecgDataDef.ecgPatData.strFilePathName.GetLength() > 0) {
			if(!CECGFile::GetMe()->ECGReadFile(&pMainFrame->m_ecgDataDef, pMainFrame->m_ecgDataDef.ecgPatData.strFilePathName)){
				CString strErrorMsg = "";
				strErrorMsg.LoadString(IDS_STRING157);
				AfxMessageBox(strErrorMsg);
				return;
			}
			
			if(pMainFrame->m_ecgDataDef.dECGDataLenRR > 0){
				CECGDraw::GetMe()->ECGSenMarkUnitMac(&pMainFrame->m_ecgDataDef);
			}else if(pMainFrame->m_ecgDataDef.ecgMacType == ECG_MACHINE_TYPE_9801_SERIES){
				CECGDraw::GetMe()->ECGSenMarkUnitMac(&pMainFrame->m_ecgDataDef);
			}else if(pMainFrame->m_ecgDataDef.ecgMacType == ECG_MACHINE_TYPE_6010_SERIES){
				CECGDraw::GetMe()->ECGSenMarkUnitMac(&pMainFrame->m_ecgDataDef);
			}
//			CECGDrawIf::GetMe()->SetFirst(TRUE);

			//			CopyPatientData(m_pPatData, &pMainFrame->m_ecgDataDef.ecgPatData);
			CECGWorkStationDoc* pDoc = ((CECGWorkStationView*)pMainFrame->GetActiveView())->GetDocument();
			pDoc->SetPathName((LPCTSTR)pMainFrame->m_ecgDataDef.ecgPatData.strFilePathName);

			((CECGWorkStationView*)pMainFrame->GetActiveView())->DrawInterface();
			pMainFrame->PatientChanged();
//			pMainFrame->DockCtrls(MAIN_INTERFACE_WAVEFORM);
		}
	}
	EndWaitCursor();

	CDialog::OnOK();
	CDialog::OnLButtonDblClk(nFlags, point);
}

void CDialogQuery::OnButtonSelectall() 
{
	m_bSelectAll = !m_bSelectAll;
	m_listQueryResult.SelectAll(m_bSelectAll);
}

void CDialogQuery::OnButtonPrintall() 
{
	CMainFrame* pMainFrame = (CMainFrame*)(AfxGetApp()->m_pMainWnd);
	CMainFrame* pMainFrameBack = pMainFrame;


	CString strMessage = "";
	strMessage.LoadString(IDS_STRING1054);
	if(pMainFrame->m_ecgDataDef.ecgPatData.strPatientID.GetLength() > 0 &&
		pMainFrame->m_ecgDataDef.ecgPatData.strName.GetLength() > 0){
			if (MessageBox(strMessage, NULL, MB_OKCANCEL) == IDCANCEL) {
				return;
			}
		}
	BeginWaitCursor();
	InitPatientData(&pMainFrame->m_ecgDataDef.ecgPatData);
	((CECGWorkStationView*)pMainFrame->GetActiveView())->DrawInterface();
	pMainFrame->PatientChanged();
	pMainFrame->ClearWaveForm();

	CStringArray strUIDArray;
	CStringArray strIDArray;
	m_listQueryResult.GetSelectedRecord(&strUIDArray, &strIDArray);

	CString strPatientID = "";
	BCDBConnection DBConn;
	char szErrorMsg[1024];
	memset(szErrorMsg, 0, 1024);
	if(!BCDBConnectDB(&DBConn, (LPCTSTR)theApp.m_strConnection, (LPCTSTR)theApp.m_strConnUserName, (LPCTSTR)theApp.m_strConnPassWord, szErrorMsg)){
		
		return;
	}
	for (int nLoop = 0; nLoop < strUIDArray.GetSize(); ++nLoop)
	{
//		PATIENT_DATA PatData = pMainFrame->m_ecgDataDef.ecgPatData;
		InitPatientData(&pMainFrame->m_ecgDataDef.ecgPatData);
		strPatientID = strUIDArray.GetAt(nLoop);
		BCDBDataSet* pKeys = NULL;
		BCDBCreateDataSet(&pKeys, szErrorMsg);

		BCDBDataElem* pDataElem = NULL;
		BCDBCreateDataElem(&pDataElem, T_PATIENT_KEY, strPatientID.GetLength(), DT_STRING, (void*)(LPCTSTR)strPatientID, szErrorMsg);
		pKeys->push_back(pDataElem);
		pDataElem = NULL;

		BCDBDataSets* pDataSets = NULL;
		BCDBCreateDataSets(&pDataSets, szErrorMsg);

		if (!BCDBQueryDBData(&DBConn, T_PATIENT, pKeys, &pDataSets, szErrorMsg)) {
			BCDBClearDataSet(pKeys, szErrorMsg);
			BCDBClearDataSets(pDataSets, szErrorMsg);
			BCDBDisconnectionDB(&DBConn, szErrorMsg);

			return;
		}
		BCDBDataSet* pDataSet = NULL;
		BCDBDataSets::iterator itDataSets = pDataSets->begin();
		for (; itDataSets != pDataSets->end(); ++itDataSets)
		{
			pDataSet = *itDataSets;
			if (pDataSet == NULL) {
				break;
			}
			BCDBDataSet::iterator itDataSet = pDataSet->begin();
			for (; itDataSet != pDataSet->end(); ++itDataSet)
			{
				pDataElem = *itDataSet;
				if (pDataElem == NULL) {
					break;
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_KEY)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strPatientKey.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_ID)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strPatientID.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_NAME)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strName.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_SEX)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strSex.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_ADDRESS)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strAddress.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_BIRTHDAY)) {
					CString strDate;
					strDate.Format("%s", (LPCTSTR)pDataElem->pValue);
					int nPosYear, nPosMonth, nYear, nMonth, nDay;
					nPosYear = strDate.Find("-");
					BOOL bNoFind = FALSE;
					if (nPosYear < 0) {
						bNoFind = TRUE;
						nPosYear = strDate.Find("/");
					}

					if (bNoFind) {
						nPosMonth = strDate.Find("/", nPosYear + 1);
					}else nPosMonth = strDate.Find("-", nPosYear + 1);
					if(nPosYear > 0 && nPosMonth > 0){
						if (bNoFind) {
							CString strTemp = strDate.Mid(0, 2);
							nMonth = atoi(strTemp);
							strTemp = strDate.Mid(nPosYear + 1, nPosMonth - nPosYear);
							nDay = atoi(strTemp);
							strTemp = strDate.Mid(nPosMonth + 1, strDate.GetLength() - nPosMonth);
							nYear = atoi(strTemp);
						}else{
							CString strTemp = strDate.Mid(0, 4);
							nYear = atoi(strTemp);
							strTemp = strDate.Mid(nPosYear + 1, nPosMonth - nPosYear);
							nMonth = atoi(strTemp);
							strTemp = strDate.Mid(nPosMonth + 1, strDate.GetLength() - nPosMonth);
							nDay = atoi(strTemp);
						}
						COleDateTime tmBirthday(nYear, nMonth, nDay, 22, 15, 0 );
						pMainFrame->m_ecgDataDef.ecgPatData.tmBirthday = tmBirthday;
					}
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_AGE)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strAge.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_HEIGHT)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strHeight.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_WEIGHT)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strWeight.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_BP)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strBP.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_POSTCODE)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strPostCode.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_PATIENT_TEL)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strTel.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				pDataElem = NULL;
			}
			pDataSet = NULL;
		}
		BCDBClearDataSets(pDataSets, szErrorMsg);

		BCDBCreateDataSets(&pDataSets, szErrorMsg);
		if (!BCDBQueryDBData(&DBConn, T_STUDY, pKeys, &pDataSets, szErrorMsg)) {
			BCDBClearDataSet(pKeys, szErrorMsg);
			BCDBClearDataSets(pDataSets, szErrorMsg);
			BCDBDisconnectionDB(&DBConn, szErrorMsg);

			return;
		}

		itDataSets = pDataSets->begin();
		int nPos, nYear, nMonth, nDay, nMin, nHour, nSec;
		if(itDataSets != pDataSets->end())
		{
			pDataSet = *itDataSets;
			if (pDataSet == NULL) {
				break;
			}
			BCDBDataSet::iterator itDataSet = pDataSet->begin();
			for (; itDataSet != pDataSet->end(); ++itDataSet)
			{
				pDataElem = *itDataSet;
				if (pDataElem == NULL) {
					break;
				}
				if (!strcmp(pDataElem->szName, T_STUDY_DATE)) {
					CString strStudyDate = (CString)(LPCTSTR)pDataElem->pValue;
					CString strTemp = "";
					nPos = strStudyDate.Find("-");
					BOOL bNoFind = FALSE;
					if (nPos < 0) {
						bNoFind = TRUE;
						nPos = strStudyDate.Find("/");
					}

					if (bNoFind) {
						strTemp = strStudyDate.Left(nPos);
						nMonth = atoi(strTemp);

						strStudyDate = strStudyDate.Right(strStudyDate.GetLength() - nPos - 1);
						nPos = strStudyDate.Find("/");
						strTemp = strStudyDate.Left(nPos);
						nDay = atoi(strTemp);
						strStudyDate = strStudyDate.Right(strStudyDate.GetLength() - nPos - 1);
						nYear = atoi(strStudyDate);

					}else{
						strTemp = strStudyDate.Left(nPos);
						nYear = atoi(strTemp);
						strStudyDate = strStudyDate.Right(strStudyDate.GetLength() - nPos - 1);
						nPos = strStudyDate.Find("-");
						strTemp = strStudyDate.Left(nPos);
						nMonth = atoi(strTemp);
						strStudyDate = strStudyDate.Right(strStudyDate.GetLength() - nPos - 1);
						nDay = atoi(strStudyDate);
					}
				}
				if (!strcmp(pDataElem->szName, T_STUDY_TIME)) {
					CString strStudyTime = (CString)(LPCTSTR)pDataElem->pValue;
					int nPos = 0; nPos = strStudyTime.Find(" ");
					strStudyTime = strStudyTime.Right(strStudyTime.GetLength() - nPos - 1);

					nPos = strStudyTime.Find(":");
					if(nPos > 0){
						CString strTemp = strStudyTime.Left(nPos);
						nHour = atoi(strTemp);
						if (nHour <= 0) {
							nHour = 12;
						}
						strStudyTime = strStudyTime.Right(strStudyTime.GetLength() - nPos - 1);
						nPos = strStudyTime.Find(":");
						strTemp = strStudyTime.Left(nPos);
						nMin = atoi(strTemp);
						if(nMin <= 0) nMin = 12;
						strStudyTime = strStudyTime.Right(strStudyTime.GetLength() - nPos - 1);
						nSec = atoi(strStudyTime);
						if(nSec <= 0) nSec = 12;
					}else{
						nHour = nMin = nSec = 12;
					}

//						strStudyTime.Format("%02d:%02d:%02d", nYear, nMonth, nDay);
//						lpRelative->SetSubItemText(0, strStudyTime);
				}
//					strStudyDate.Format("%04d-%02d-%02d", nYear, nMonth, nDay);
				
				if (!strcmp(pDataElem->szName, T_STUDY_ID)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strStudyID.Format("%s", (LPCTSTR)pDataElem->pValue);
				}

				if (!strcmp(pDataElem->szName, T_STUDY_BEDNO)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strBedNo.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_STUDY_CLINICNO)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strClinicNo.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_STUDY_HOSPNO)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strHospNo.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_STUDY_PHYSICAL)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strPhysical.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_STUDY_DR)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strDR.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_STUDY_DEPART)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strDepart.Format("%s", (LPCTSTR)pDataElem->pValue);
				}

				if (!strcmp(pDataElem->szName, T_STUDY_DATA)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strFilePathName.Format("%s", (LPCTSTR)pDataElem->pValue);
				}

				if (!strcmp(pDataElem->szName, T_STUDY_DESC)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strMemo.Format("%s", (LPCTSTR)pDataElem->pValue);
				}
				if (!strcmp(pDataElem->szName, T_STUDY_RESULT)) {
					pMainFrame->m_ecgDataDef.ecgPatData.strStudyResultManu.Format("%s", (LPCTSTR)pDataElem->pValue);
				}

				pDataElem = NULL;
			}

			pMainFrame->m_ecgDataDef.ecgPatData.tmStudyDateTime = COleDateTime(nYear, nMonth, nDay, nHour, nMin, nSec);
			pDataSet = NULL;

			CString strECGShare = "";
			CIniReadWrite::GetMe()->LoadString(DEF_GENERAL_SETTING, DEF_ECGSHARE, &strECGShare);
			if(!strECGShare.CompareNoCase("TRUE")){
				CString strShortTerm = "";
				CIniReadWrite::GetMe()->LoadString(DEF_GENERAL_SETTING, DEF_SHORTTERM, &strShortTerm);
				pMainFrame->m_ecgDataDef.ecgPatData.strFilePathName.Format("%s\\%s\\%s", strShortTerm, pMainFrame->m_ecgDataDef.ecgPatData.strPatientID, pMainFrame->m_ecgDataDef.ecgPatData.strStudyID);
			}
			BCDBClearDataSet(pKeys, szErrorMsg);
		}

		BCDBClearDataSets(pDataSets, szErrorMsg);

		if (pMainFrame->m_ecgDataDef.ecgPatData.strFilePathName.GetLength() > 0) {
			if(!CECGFile::GetMe()->ECGReadFile(&pMainFrame->m_ecgDataDef, pMainFrame->m_ecgDataDef.ecgPatData.strFilePathName)){
				CString strErrorMsg = "";
				strErrorMsg.LoadString(IDS_STRING157);
				AfxMessageBox(strErrorMsg);
				return;
			}
			
			if(pMainFrame->m_ecgDataDef.dECGDataLenRR > 0){
				CECGDraw::GetMe()->ECGSenMarkUnitMac(&pMainFrame->m_ecgDataDef);
			}else if(pMainFrame->m_ecgDataDef.ecgMacType == ECG_MACHINE_TYPE_9801_SERIES){
				CECGDraw::GetMe()->ECGSenMarkUnitMac(&pMainFrame->m_ecgDataDef);
			}else if(pMainFrame->m_ecgDataDef.ecgMacType == ECG_MACHINE_TYPE_6010_SERIES){
				CECGDraw::GetMe()->ECGSenMarkUnitMac(&pMainFrame->m_ecgDataDef);
			}
			//			CECGDrawIf::GetMe()->SetFirst(TRUE);
			
			//			CopyPatientData(m_pPatData, &pMainFrame->m_ecgDataDef.ecgPatData);
			CECGWorkStationDoc* pDoc = ((CECGWorkStationView*)pMainFrame->GetActiveView())->GetDocument();
			pDoc->SetPathName((LPCTSTR)pMainFrame->m_ecgDataDef.ecgPatData.strFilePathName);
			
			//((CECGWorkStationView*)pMainFrame->GetActiveView())->DrawInterface();
			//pMainFrame->PatientChanged();
			//			pMainFrame->DockCtrls(MAIN_INTERFACE_WAVEFORM);
			::SendMessage(pMainFrame->m_hWnd, WM_COMMAND, ID_TOOLBAR_PRINT, NULL);
		}
	}

	if(!BCDBDisconnectionDB(&DBConn, szErrorMsg)){
		return;
	}
	
	InitPatientData(&pMainFrame->m_ecgDataDef.ecgPatData);
	((CECGWorkStationView*)pMainFrame->GetActiveView())->DrawInterface();
	//pMainFrame->PatientChanged();
	pMainFrame->PatientChanged((char*)pMainFrameBack);
	pMainFrame->ClearWaveForm();

	EndWaitCursor();
}
